<template>
  <div class="div">
    <div class="div1">
      <el-form ref="form" :model="form" label-width="120px" :rules="rules">
        <div class="left">
          <el-form-item label="商品名称" class="item" prop="goodsName">
            <el-input v-model="form.goodsName"/>
          </el-form-item>
          <el-form-item label="是否是时令蔬菜" class="item" prop="or">
            <select name="cate" v-model="select" style="font-size: 20px">
              <option disabled selected style="display: block;">是否是时令蔬菜</option>
              <option v-for="(item,index) in arr "
                      :key="index"
                      :value="item.name">{{ item.name }}
              </option>
            </select>

          </el-form-item>
          <el-form-item label="商品类别" class="item" prop="goodsType" style="width: 1000px">
            <el-cascader :options="type" :props="{ value: 'id',label: 'name'}" v-model="form.goodsType">
              <template #default="{ node, data }">
                <span>{{ data.name }}</span>
                <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
              </template>
            </el-cascader>
          </el-form-item>
          <el-form-item label="商品库存" class="item" prop="stock">
            <el-input placeholder="0" v-model="form.stock"/>
          </el-form-item>
          <el-form-item label="商品价格" class="item" prop="goodsPrice">
            <el-input placeholder="0.00" @keydown="handleInput2" v-model="form.goodsPrice"/>
          </el-form-item>
          <el-form-item label="商品图片" prop="img">
            <!--            <el-upload id="pic" action="#"-->
            <!--                       list-type="picture-card"-->
            <!--                       :auto-upload="false"-->
            <!--                       :on-change="handleChange"-->
            <!--                       :before-upload="beforeUpload"-->
            <!--                       ref="upload"-->
            <!--                       :on-remove="handleRemove"-->
            <!--                       :limit="2"-->
            <!--                       :class="{ disabled: uploadDisabled }">-->
            <!--              <el-icon>-->
            <!--                <Plus/>-->
            <!--              </el-icon>-->
            <!--            </el-upload>-->
            <el-upload
                v-model:file-list="fileList"
                class="upload-demo"
                action="#"
                multiple
                accept=".jpg,.jpeg,.png,.JPG,.JPEG"
                :auto-upload="false"
                :on-remove="handleRemove"
                :limit="3"
                :on-exceed="handleExceed"
            >
              <el-button type="primary">点击上传图片</el-button>
              <template #tip>
                <div class="el-upload__tip">
                  jpg/png files with a size less than 500KB.
                </div>
              </template>
            </el-upload>
          </el-form-item>
          <div class="bnt">
            <el-form-item>
              <el-button type="primary" @click="onSubmit">发布</el-button>
              <el-button>取消</el-button>
            </el-form-item>
          </div>
        </div>

        <div class="right">
          <el-form-item label="商品详情" class="item2" prop="goodsDescription">
            <s-editor @change="getUrl1" :content="form.goodsDescription"/>
          </el-form-item>
        </div>
      </el-form>
    </div>

  </div>
</template>

<script >
// import {Plus} from '@element-plus/icons-vue'
import request from "@/utils/request";
import {reactive} from "vue";
import {ElMessage} from "element-plus";
import sEditor from '../components/background/Editor'

export default {
  name: "publishGoods",
  components: {
    // Plus,
    sEditor
  },
  data() {
    const validateName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入商品名称'));
      } else if (value.toString().match("[^\u4e00-\u9fa5a-zA-Z0-9]")) {
        callback(new Error('商品名称填写有误，不能包含特殊字符'));
      } else {
        callback();
      }
    };
    const validatePrice = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入商品价格'));
      } else {
        if (value.toString().match("[^0-9\\.]") || value.toString().match("^\\.")) {
          callback(new Error('请输入正确的商品价格'));
        } else {
          callback();
        }
      }
    };
    const validateGoodsType = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请选择商品类型'));
      } else {
        callback();
      }
    };
    return {
      fileList: [],
      type: [],
      arr: [{name: '是'}, {name: '否'}],
      select: '否',
      form: {
        stock: '',
        goodsName: '',
        goodsType: '',
        goodsPrice: '',
        goodsDescription: '',
      },
      rules: reactive({
        goodsName: [{required: true, validator: validateName, trigger: 'blur'},
          {min: 2, max: 20, message: '长度必须在2-20之内', trigger: 'blur'}],
        goodsPrice: [{required: true, validator: validatePrice, trigger: 'blur'}],
        goodsType: [{type: 'array', required: true, validator: validateGoodsType, trigger: 'change'}],
        goodsDescription: [{required: true, message: '商品描述不能为空', trigger: 'change'}],
      })
    }
  },
  methods: {
    handleExceed(files, uploadFiles) {
      ElMessage.warning(
          `只能上传${files.length}张图片`
      )
    },
    // beforeUpload(file) {
    //   if (file.type !== 'image/jpeg') {
    //     ElMessage.error('图片格式不是jpeg格式的!')
    //     return false
    //   } else if (file.size / 1024 / 1024 > 4) {
    //     ElMessage.error('图片大小超过了4MB!')
    //     return false
    //   } else {
    //     let formData = new FormData();
    //     formData.append("goodsName", this.form.goodsName)
    //     formData.append("img", file)
    //     formData.append("goodsDescription", this.form.goodsDescription)
    //     let price = this.form.goodsPrice
    //     let index = price.indexOf(".");
    //     if (index === -1) {
    //       price = price + ".00"
    //     } else {
    //       let len = price.length;
    //       let poor = len - index - 1;
    //       if (poor < 2) {
    //         for (var i = 0; i < 2 - poor; i++) {
    //           price = price + "0";
    //         }
    //       }
    //     }
    //     formData.append("goodsPrice", price)
    //     formData.append("goodsType", this.form.goodsType)
    //     request.post("http://localhost:8086/seller/publishGoods", formData).then(res => {
    //       if (res.flag) {
    //         this.$message({
    //           type: 'success',
    //           message: res.msg
    //         })
    //       } else {
    //         this.$message.error(res.msg);
    //       }
    //     }).finally(() => {
    //       request.get("http://localhost:8086/goods/checkGoodsExists").then(res => {
    //         if (res.data == 1) {
    //           this.goodsExists = true;
    //         } else {
    //           this.goodsExists = false;
    //         }
    //       });
    //       this.form = {
    //         goodsName: '',
    //         goodsType: '',
    //         goodsPrice: '',
    //         goodsDescription: '',
    //       }
    //     })
    //     return false;
    //   }
    // },
    handleRemove() {
      this.uploadDisabled = false;
    },
    onSubmit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          let formData = new FormData();
          formData.append("goodsName", this.form.goodsName)
          this.fileList.forEach(
              (val, index) => {
                formData.append("file", val.raw);
              }
          )
          formData.append("goodsDescription", this.form.goodsDescription)
          let price = this.form.goodsPrice
          let index = price.indexOf(".");
          if (index === -1) {
            price = price + ".00"
          } else {
            let len = price.length;
            let poor = len - index - 1;
            if (poor < 2) {
              for (var i = 0; i < 2 - poor; i++) {
                price = price + "0";
              }
            }
          }
          formData.append("goodsPrice", price)
          formData.append("goodsType", this.form.goodsType)
          formData.append("stock",this.form.stock)
          formData.append("select",this.select)
          request.post("http://localhost:8086/seller/publishGoods2", formData).then(res => {
            if (res.flag) {
              this.$message({
                type: 'success',
                message: res.msg
              })
            } else {
              this.$message.error(res.msg);
            }
          }).finally(() => {
            this.form = {
              goodsName: '',
              goodsType: '',
              goodsPrice: '',
              goodsDescription: '',
            }
          })
        }
      })
    },
    initType() {
      request.get("http://localhost:8087/vegetablesType/getAllType").then(res => {
        if (res.flag) {
          this.type = res.data
          this.$message({
            type: 'success',
            message: res.msg
          })
        } else {
          this.$message.error(res.msg);
        }
      })
    },
    handleInput2(e) {
      // 通过正则过滤小数点后两位
      e.target.value = (e.target.value.match(/^\d*(\.?\d{0,1})/g)[0]) || null
    },
    getUrl1(path){
      this.form.goodsDescription=path;//获取子组件中的数据
    },
  },
  created() {
    this.initType();
  },
}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.div {
  /*background-color: #E0EEE0;*/
}

.div1 {
  display: flex;
  text-align: center;
}

.left {
  float: left;
  width: 400px;
}

.right {
  margin-left: 420px;
}

.item {
  width: 400px;
  margin-top: 20px;
  margin-left: 10px;
}

.item2 {
  width: 600px;
  margin-top: 60px;
  margin-left: 10px;
}

.bnt {
  position: absolute;
  left: 45%;
  bottom: 10px;
}

.h1 {
  text-align: center;
  margin-top: 20px;
}
</style>

<style>

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

</style>
